<template>
  <!-- 资质信息 -->
  <vxe-table
    class="qualification-info"
    show-overflow
    border
    ref="table"
    row-id="id"
    :auto-resize="true"
    :print-config="{}"
    :export-config="{}"
    :edit-config="{}"
    :edit-rules="editRules"
    :data="tableList">
    <vxe-colgroup title="资质列表" align="center">
      <vxe-column title="资质名称" field="qualification" min-width="200px">
        <template #default="{ row }">
          <span class="asterisk" v-if="row.mustHave === '1'">*</span>
          {{row.qualification}}
        </template>
      </vxe-column>
      <vxe-column title="生效日期"  field="effectiveDate" min-width="240px">
        <template #default="{ row }" v-if="!readonly">
          <el-date-picker
            v-model="row.effectiveDate"
            :value-format="'yyyy-MM-dd HH:mm:ss'"
            type="datetime"
            :picker-options="getEffectiveDateOpt(row)"
            @change="handleChange"
            placeholder="选择生效日期">
          </el-date-picker>
        </template>
      </vxe-column>
      <vxe-column title="失效日期" field="expiryDate" min-width="240px">
        <template #default="{ row }" v-if="!readonly">
          <el-date-picker
            v-model="row.expiryDate"
            :value-format="'yyyy-MM-dd HH:mm:ss'"
            type="datetime"
            :picker-options="getExpiryDateOpt(row)"
            @change="handleChange"
            placeholder="选择失效日期">
          </el-date-picker>
        </template>
      </vxe-column>
      <vxe-column title="资质附件 （只能上传pdf格式文件或图片，单文件不能超过5Mb）" field="annex" min-width="210px">
        <template #default="{ row, _rowIndex }">
          <span v-if="row.annex">
            <a class="download-btn" @click="handlePreview(row)">附件预览</a>
            <AnnexDownloadButton v-model="row.annex" buttonText="附件下载" :fileName="row.qualification" />
            <el-tooltip effect="dark" content="删除" v-if="!readonly">
              <i class="delete-icon el-icon-close" @click="handleDelteAnnex(row, _rowIndex)"></i>
            </el-tooltip>
          </span>
        </template>
      </vxe-column>
      <vxe-column title="操作" width="190px" v-if="!readonly">
        <template #default="{ row, _rowIndex }">
          <AnnexUploadButton buttonType="text" typeList="pdf/png/jpg/jpge" :sizeLimit="5" @onUploaded="(params)=>{handleUploaded(params, row, _rowIndex)}" />
          <el-button class="action-btn" v-if="row.quaTypeNo" type="text" @click="insertRow(row, _rowIndex)">增加资质行</el-button>
          <el-button class="action-btn" v-if="!row.quaTypeNo" type="text" @click="removeRow(row, _rowIndex)">删除行</el-button>
        </template>
      </vxe-column>
    </vxe-colgroup>
  </vxe-table>
</template>

<script>
import { qualificationInformation } from '@/pages/supplier/constants'
import AnnexUploadButton from '@/pages/supplier/components/annexUploadButton' // 上传附件按钮
import AnnexDownloadButton from '@/pages/supplier/components/annexDownloadButton' // 下载附件按钮
import { previewSupplierQualificationService } from '@/api/supplier/management/supplierQualification'
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';
const { TABLE_COLUMNS } = qualificationInformation

export default {
  components: {
    AnnexUploadButton,
    AnnexDownloadButton,
  },
  props: {
    readonly: { // 表是否开启禁用
      type: Boolean,
      default: false
    },
    dataSource: { // 数据源
      type: Array,
      default () {
        return [];
      }
    },
    rules: { type: Object, default () { return null } }
  },
  computed: {
    toolbarConfig () {
      return {}
    },
    editConfig () {
      return {}
    },
    editRules () {
      const validator = ({ cellValue, row, column }) => {
        if (row.mustHave === '1') {
          // 1必填 2选填
          if (column.field === 'effectiveDate' && !cellValue) {
            return new Error(`请选择${row.qualification}生效日期`)
          }
          if (column.field === 'expiryDate' && !cellValue) {
            return new Error(`请选择${row.qualification}失效日期`)
          }
          if (column.field === 'annex' && !cellValue) {
            return new Error(`请上传${row.qualification}资质附件`)
          }
          if (row.expiryDate && row.effectiveDate) {
            const expiryDate = new Date(row.expiryDate)
            const effectiveDate = new Date(row.effectiveDate)
            if (effectiveDate>expiryDate) {
              return new Error(`失效日期不能早于生效日期`)
            }
          }
        } else if (row.mustHave === '2') {
          if (row.annex) {
            if (column.field === 'effectiveDate' && !cellValue) {
              return new Error(`请选择${row.qualification}生效日期`)
            }
            if (column.field === 'expiryDate' && !cellValue) {
              return new Error(`请选择${row.qualification}失效日期`)
            }
            if (row.expiryDate && row.effectiveDate) {
              const expiryDate = new Date(row.expiryDate)
              const effectiveDate = new Date(row.effectiveDate)
              if (effectiveDate>expiryDate) {
                return new Error(`失效日期不能早于生效日期`)
              }
            }
          }
        }
      }
      if (this.readonly) {
        return {}
      }
      return {
        effectiveDate: [{ validator }],
        expiryDate: [{ validator }],
        annex: [{ validator }],
      }
    }
  },
  data () {
    return {
      valid: true,
      exporting: false,
      tableList: this.dataSource,
      tableColumns: TABLE_COLUMNS,
    };
  },
  created () {
    // this.validate()
  },
  watch: {
    dataSource: {
      handler (newVal, oldVal) {
        this.tableList = newVal
      },
      immediate: true,
      deep: true
    },
    tableList: {
      handler (newVal, oldVal) {
        if (newVal) {
          this.$emit('change', { value: newVal, prop: 'supplierQualificationBillList' })
        }
      },
      immediate: true,
      deep: true
    },
  },
  mounted () {
  },
  methods: {
    getEffectiveDateOpt (row) {
      if (row.expiryDate) {
        let expiry = new Date(row.expiryDate)
        return {
          disabledDate (time) {
            return time.getTime() > expiry.getTime();
          },
        }
      }
      return {}
    },
    getExpiryDateOpt (row) {
      if (row.effectiveDate) {
        let effective = new Date(row.effectiveDate)
        return {
          disabledDate (time) {
            return time.getTime() < effective.getTime();
          },
        }
      }
      return {}
    },
    // 增加资质行
    insertRow (row, index) {
      const obj = {
        qualificationId: row.qualificationId,
        qualification: row.qualification,
        effectiveDate: '',
        expiryDate: '',
        annex: ''
      }
      const [first] = this.tableList;
      if (first.supplierId) {
        const { supplierId, supplierCode } = first
        Object.assign(obj, { supplierId, supplierCode })
      }
      this.$refs.table.insertAt(obj, this.tableList[index + 1])
      this.tableList.splice(index + 1, -1, obj)
    },
    // 删除行
    removeRow (row, index) {
      this.$refs.table.remove(row)
      this.tableList.splice(index, 1)
    },
    // 上传资质附件
    handleUploaded ({ response, file }, row, index) {
      const { result } = response
      row.annex = result
      this.handleChange()
    },
    // 删除资质附件
    handleDelteAnnex (row) {
      row.annex = '';
      this.handleChange()
    },
    handleChange () {
      this.$refs.table.clearValidate()
    },
    getValidate () {
      return this.$refs.table.validate(true)
    },
    getData () {
      return this.supplierQualificationBillList
    },
    // 附件预览
    handlePreview (row) {
      const fileTypes = ['bmp', 'jpg', 'jpeg', 'png'];
      const fileSuffixArr = row.annex.split('.')
      const fileSuffix = fileSuffixArr[fileSuffixArr.length - 1]
      if (!fileTypes.includes(fileSuffix)) {
        return this.$message.error('仅支持图片格式文件预览。')
      }
      this.previewFile(row.annex)
    },
    // 预览附件
    async previewFile (annex) {
      const res = await previewSupplierQualificationService({ annex })
      if (isResponseSuccess(res)) {
        window.open(res.result)
      }
    },
  },
}
</script>

<style lang="less" scoped>
.action-btn {
  margin: 0 4px;
}
.asterisk {
  color: #F56C6C;
}
.delete-icon {
  color: red;
  cursor: pointer;
}
.download-btn {
  font-size: 12px;
  margin-left: 5px;
}
</style>
